package com.yyq.adms.yyb.patent.action;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.yyq.adms.bzgf.pojo.StandardFormation;
import com.yyq.adms.util.JxlsUtil;
import com.yyq.adms.util.JxlsVo;
import com.yyq.adms.util.ValidateUtil;
import com.yyq.adms.util.ValidateVo;
import com.yyq.adms.yyb.patent.bpo.OwnPatentBpo;
import com.yyq.adms.yyb.patent.bpo.PatentApplyBpo;
import com.yyq.adms.yyb.patent.pojo.OwnPatent;
import com.yyq.adms.yyb.patent.pojo.PatentApply;
import com.yyq.adms.yyb.softwareManager.pojo.ReportCertificate;
import com.yyq.adms.yyb.utils.YYBUtils;
import com.yyq.sos.action.BaseAction;
import com.yyq.sos.constants.ActionType;
import com.yyq.sos.constants.Constants;
import com.yyq.sos.permission.LoginUser;
import com.yyq.sos.util.PermissionsUtil;
import com.yyq.sos.util.page.PageFormData;

/**
 * 专利申请Action 层
 * 
 * @author 杨应滨
 * @2012-12-3
 * 
 */
@Controller("patentApplyAction")
@Scope("prototype")
public class PatentApplyAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private PatentApply po = new PatentApply();

	private PatentApplyBpo bpo;

	private OwnPatentBpo ownPatentBpo;

	public OwnPatentBpo getOwnPatentBpo() {
		return ownPatentBpo;
	}

	@Resource(name = "ownPatentBpo")
	public void setOwnPatentBpo(OwnPatentBpo ownPatentBpo) {
		ownPatentBpo.setCls(OwnPatent.class);
		this.ownPatentBpo = ownPatentBpo;
	}

	public PatentApply getPo() {
		return po;
	}

	public void setPo(PatentApply po) {
		this.po = po;
	}

	public PatentApplyBpo getBpo() {
		return bpo;
	}

	@Resource(name = "patentApplyBpo")
	public void setBpo(PatentApplyBpo bpo) {
		bpo.setCls(po.getClass());
		this.bpo = bpo;
	}

	public static long getSerialversionuid() {
		return serialVersionUID;
	}
	
	/*public String goAdd()
	{
		String[] type = (String[])this.getFormValue("type");
		if(type != null && "publish".equals(type[0])){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			this.setFormValue("nowDate", sdf.format(new Date()));
			String sentDep = po.getSentDep();
			po = (StandardFormation)bpo.findByPk(po.getId());
			po.setSentDep(sentDep);
			this.setObj(po);
			return "publishAdd";
		}else{
			return ActionType.ACTION_GO_ADD;
		}
	}*/
	
	@Override
	public String update() {
		String state = this.po.getNowState();
		Long sourceID = this.po.getId();
		String result =  super.update();
System.out.println("报送单位========>"+po.getSentDepName());
		if (state!=null && state.equals("2")) {
			// 已获批 需保存
			String tableName = ownPatentBpo
					.getTableName(OwnPatent.class);
			List _tempList = ownPatentBpo.searchSql("select * from " + tableName + " where sourceid = " + sourceID);

			if (_tempList.size() == 0) {
				//this.setMsg("{processId:\"2\",msg:\"更新成功\",sourceId:\""+sourceID+"\",sentDep:\""+po.getSentDep()+"\"}");
				
				OwnPatent target = new OwnPatent();
				target.setPatentName(po.getPatentName());
				target.setPatentCode(po.getApplyCode());
				target.setPatentType(po.getPatentType());
				target.setApplicant(po.getApplicant());
				target.setInventor(po.getInventor());
				target.setCatchWay(po.getApplyType());
				target.setSentDepName(po.getSentDepName());
				po.setResultDate(new Date());
				target.setCatchDate(po.getResultDate());
//				target.setSentDep(po.getSentDep());
				target.setSourceID(sourceID.intValue());
				//target.setCatchDate(new Date());
				target.setBelongPlateFormID(po.getBelongPlateFormID());
				Serializable id = ownPatentBpo.save(target);
				if(id != null){
					String sentDep = po.getSentDep();
					List sds = new ArrayList();
					processSentDep(sds, tableName, sentDep, id);
					if(sds.size()>0){
						Serializable[] ids = bpo.save(sds.toArray());
					}
				}

			}
		}
		return result;
	}

	@Override
	public String add() {
		String hql = "from PatentApply where patentName='"+po.getPatentName()+"' and patentType='"+po.getPatentType()+"'";
		long count = bpo.count(hql);
		if(count > 0){
			this.setMsg("{processId:\"-1\",msg:\"(专利名称+专利类型)与数据库里数据重复了\"}");
			return ActionType.ACTION_MSG;
		}else{
			return super.add();
		}
	}
	
	/*@Override
	public String batchAdd() {
		if(this.getAccessory() != null){
			String msg = "";
			if("xls".equals(this.getAccessoryFileName().substring(this.getAccessoryFileName().lastIndexOf(".")+1))){
				try {
					List<Map<String, JxlsVo>> data = JxlsUtil.getInstance().transfromData(this.getAccessory());
					Map<String,ValidateVo> vMap = ValidateUtil.getInstance().getValidatesByClassName(po.getClass().getName());
					List list = new ArrayList();
					LoginUser user = (LoginUser)this.getSession().getAttribute(Constants.LOGIN_USER);
					List repeatDB = new ArrayList();
					StringBuffer errMsg = JxlsUtil.getInstance().validateXls(data, vMap, po.getClass(), list,user,repeatDB);
					bpo.validateUniquene(data, errMsg);
					msg = errMsg.toString();
					if(msg.toString().equals("")){
						if(list.size()>0){
							Serializable[] ids = bpo.save(list.toArray());
							if(ids != null){
								msg = "添加成功！";
							}else{
								msg = "添加失败！";
							}
						}else{
							msg = "批量添加数据为空，请添加数据!";
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				this.setMsg(msg);
			}else{
				this.setMsg("文件类型不支持!");
			}
		}
		return ActionType.ACTION_BATCH_ADD;
	}*/
	
	public String execute() throws Exception {
		super.setBpo(bpo);
		super.setObj(po);
		String s = super.execute();
		this.setPo((PatentApply) super.getObj());
		return s;
	}

	@Override
	public String data() {
		LoginUser user = (LoginUser)this.getSession().getAttribute(Constants.LOGIN_USER);
		String moduleName = getModuleName(this.getRequest().getRequestURI());
		boolean isPerm = PermissionsUtil.checkPermissionByCode(this.getSession(), moduleName,Constants.RIGHT_GLOBAL);
		String hql = "";
		if(user.getUserId().intValue()==1 || isPerm){
			hql = "from PatentApply order by applyDate desc";
		}else{
			hql = "from "+po.getClass().getName()+" obj where obj.maintainDep="+user.getOrgId()+" or EXISTS(from RecordSentDep rsd where obj.id=rsd.sourceRecordId and rsd.yyqTableName='"+bpo.getTableName(po.getClass())+"' and rsd.sentDepId="+user.getOrgId()+") order by obj.applyDate desc";
		}
		this.setFormData(bpo.searchPage(hql, getPageForm().getPageNo(), getPageForm().getPageSize()));
		
		processData();

		return ActionType.ACTION_DATA_LIST;
	}

	private void processData() {
		PageFormData formData = this.getFormData();
		List _templist = formData.getData();
		List _list = new ArrayList();
		for (int i = 0; i < _templist.size(); i++) {
			PatentApply _declare = (PatentApply) _templist.get(i);

			Date _date = _declare.getApplyDate();

			String _year = YYBUtils.getFormatDateYear(_date);
			_declare.setBelongYear(_year);
			_list.add(_declare);
		}
		if (_list.size() > 0)
			formData.setData(_list);
	}
	
	public String search()
	{
		String searchProperty = ((String[])this.getFormValue("searchProperty"))[0];
		String searchKey = ((String[])this.getFormValue("searchKey"))[0];
		LoginUser user = (LoginUser)this.getSession().getAttribute(Constants.LOGIN_USER);
		String moduleName = getModuleName(this.getRequest().getRequestURI());
		boolean isPerm = PermissionsUtil.checkPermissionByCode(this.getSession(), moduleName,Constants.RIGHT_GLOBAL);
		String hql = "";
		if(user.getUserId().intValue()==1 || isPerm){
			if("sentDep".equals(searchProperty)){
				hql = "select distinct obj from "+po.getClass().getName()+" obj,RecordSentDep rsd,SysDepts d where " +
					  " obj.id=rsd.sourceRecordId and rsd.sentDepId=d.id and rsd.yyqTableName='"+bpo.getTableName(po.getClass())+"' and d.deptCname like '%"+searchKey+"%' order by applyDate desc";
			}else{
				hql = "from "+po.getClass().getName()+" where "+searchProperty+" like '%"+searchKey+"%' order by applyDate desc";
			}
		}else{
			hql = "from "+po.getClass().getName()+" obj where (obj.maintainDep="+user.getOrgId()+" or EXISTS(from RecordSentDep rsd where obj.id=rsd.sourceRecordId and rsd.yyqTableName='"+bpo.getTableName(po.getClass())+"' and rsd.sentDepId="+user.getOrgId()+")) and obj."+searchProperty+" like '%"+searchKey+"%' order by obj.applyDate desc";
		}
		this.setFormData(bpo.searchPage(hql, this.getPageForm().getPageNo(), this.getPageForm().getPageSize()));
		processData();
		return ActionType.ACTION_DATA_LIST;
	}

}
